<template>
    <div>
        <el-dialog title="添加销售订单" v-model="props.visible" @close="handleClose" @open="handleOpen" width="70%">
            <!-- 表单数据 -->
            <el-form :model="form" ref="refFormRef" :rules="rules" >
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="订单名称" prop="salesOrderName">
                            <el-input v-model="form.salesOrderName" placeholder="请输入订单名称"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="客户编码" prop="customerCode">
                            <el-input v-model="form.customerCode" placeholder="请选择客户">
                                <template #append>
                                    <el-button type="primary" :icon="Search" @click="selectClient"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>


                    <el-col :span="6">
                        <el-form-item label="订货日期" prop="salesOrderDate">
                            <el-date-picker v-model="form.salesOrderDate" type="date" placeholder="订货日期"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="交货日期" prop="deliveryDate">
                            <el-date-picker v-model="form.deliveryDate" type="date" placeholder="交货日期"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="订单类型" prop="orderType">
                            <el-select v-model="form.orderType" placeholder="请选择订单类型">
                                <el-option label="客户订单" value="0"></el-option>
                                <el-option label="备货订单" value="1"></el-option>
                                <el-option label="样品订单" value="2"></el-option>
                                <el-option label="退货订单" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="form.remark" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 分割线 -->
            <el-row :gutter="20">
                <el-divider>
                    <span>销售订单产品列信息</span>
                </el-divider>
            </el-row>
            <!-- 按钮 -->
            <el-row :gutter="20">
                <el-button type="primary" plain :icon="Plus" @click="addItem">新增</el-button>
                <el-button type="danger" plain :icon="Delete" @click="deleteItem" :disabled="isDeleteRow">删除</el-button>
            </el-row>
            <!-- 表格 -->

            <el-table :data="selectProduct" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column label="序号" type="index" width="55" />
                <el-table-column label="产品编码" prop="productCode">
                    <template #default="scope">
                        <el-input v-model="scope.row.productCode" placeholder="请输入产品编码">
                            <template #append>
                                <el-button :icon="Search" @click="searchProduct(scope.row)" />
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" prop="productName">
                    <template #default="scope">
                        <el-input v-model="scope.row.productName" placeholder="请输入产品名称"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="订货数量" prop="salesOrderQuantity">
                    <template #default="scope">
                        <el-input v-model="scope.row.salesOrderQuantity" placeholder="请输入订货数量"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="单价" prop="amount">
                    <template #default="scope">
                        <el-input v-model="scope.row.amount" placeholder="请输入单价"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="金额" prop="productTotalPrice">
                    <template #default="scope">
                        <el-input v-model="scope.row.productTotalPrice" placeholder="0" readonly disabled></el-input>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="saveOrder">保存</el-button>
                    <el-button @click="handleClose">
                        取消
                    </el-button>
                </div>
            </template>

        </el-dialog>
        <SearchProduct :productVisible="productVisible" @productSelect="handleProductSelect" :index="index"></SearchProduct>
        <CustomerSelectionDialog :CustomerDialog="CustomerDialog" @close-dialog="closeCustomer" @rowDataA="getCustomer">
        </CustomerSelectionDialog>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import SearchProduct from './SearchProduct.vue';
import CustomerSelectionDialog from '@/components/CustomerOrders/CustomerSelectionDialog.vue'
import { ElMessage } from "element-plus";
import { saveProduct } from '@/apis/index'
const productVisible = ref(false); //产品选择弹窗
const CustomerDialog = ref(false) //客户选择框

const index = ref(null); //产品新增位置的索引
const emits = defineEmits(['closeInsertDialog']);
const isDeleteRow = ref(true); //是否删除行
const refFormRef = ref(null); //引用表单实例
const props = defineProps({
    visible: Boolean,
})
const form = ref({
    salesOrderId: null,
    salesOrderCode: null,
    salesOrderName: null,
    customerId: null,
    customerCode:null,
    salesOrderDate: null,
    deliveryDate: null,
    orderType: null,
    remark: null,
    salesOrderItems: []
})
const selectProduct = ref([]); // 选中的产品列表

// 收集选中行的索引，用于删除选中行
const productIndex = ref([])

const rules = reactive({
    salesOrderCode: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
    salesOrderName: [{ required: true, message: '请输入订单名称', trigger: 'blur' }],
    customerCode: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    salesOrderDate: [{ required: true, message: '请选择订单日期', trigger: 'blur' }],
    deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'blur' }],
    orderType: [{ required: true, message: '请选择订单类型', trigger: 'blur' }]
})

//监听数量和单价变化，计算金额
watch(
    () => selectProduct.value.map(product => ({
        productQuantity: product.salesOrderQuantity,
        productPrice: product.amount
    })),
    (newValues) => {
        newValues.forEach((value, index) => {
            selectProduct.value[index].productTotalPrice = value.productQuantity * value.productPrice;
        });
    },
    { deep: true }
);


//添加一个空对象
const addItem = () => {
    selectProduct.value.push(CreateItem())
}

// 删除选中行数据
const deleteItem = () => {
    if (productIndex.value.length == selectProduct.value.length) {
        selectProduct.value = []
    } else {
        for (let i = 0; i < productIndex.value.length; i++) {
            selectProduct.value.splice(productIndex.value[i] - 1, 1)
        }
    }
    productIndex.value = []
}

// 所有行都可以被选中
const selectable = () => true;
// 删除选中行
const handleSelectionChange = (val) => {
    isDeleteRow.value = !val.length;
    productIndex.value = val.map(item => item.index);
}
// 构建对象
function CreateItem() {
    return {
        index: selectProduct.value.length + 1,
        productId: null,
        productCode: null,
        productName: null,
        salesOrderQuantity: 0,
        amount: 0,
    }
}



const handleOpen = () => {
    resetForm() //重置表单
    
    // 清除验证规则
    refFormRef.value.clearValidate();
}

//抛出关闭事件
const handleClose = () => {
    emits('closeInsertDialog')
}
//打开搜索产品弹窗
const searchProduct = (row) => {
    console.log("点击数据",row)
    index.value = row.index
    productVisible.value = !productVisible.value;
}
// 处理选择的产品
const handleProductSelect = (ProductRow,index) => {
    productVisible.value = false;
    if (ProductRow.productName) {
        const { materialProductCode, productName, materialNo } = ProductRow;
        selectProduct.value[index-1].productCode = materialProductCode
        selectProduct.value[index-1].productName = productName
        selectProduct.value[index-1].productId = materialNo
    }
    console.log(selectProduct.value)
}

//关闭新增弹窗
const closeInsertDialog = () => {

}
// 重置表单
const resetForm = () => {
    form.value.salesOrderId = null;
    form.value.salesOrderCode = null;
    form.value.salesOrderName = null;
    form.value.customerId = null;
    form.value.customerCode = null;
    form.value.salesOrderDate = null;
    form.value.deliveryDate = null;
    form.value.orderType = null;
    form.value.remark = null;
    form.value.salesOrderItems = []

    selectProduct.value = []
    productIndex.value = []
}

// 保存订单
const saveOrder = () => {
    refFormRef.value.validate(async valid => {
        if (valid) {
            for (let i = 0; i < selectProduct.value.length; i++) {
                const { productId, productCode, productName, salesOrderQuantity, amount } = selectProduct.value[i]
                form.value.salesOrderItems.push({ productId, productCode, productName, salesOrderQuantity, amount })
            }
            form.value.salesOrderItems = form.value.salesOrderItems.filter(item => item.productId != null)
            await saveProduct(form.value)
            ElMessage.success('保存成功')
            emits('closeInsertDialog')
        } else {
            ElMessage.error('表单填写不正确，请检查')
        }
    })
}

//打开客户选择框
const selectClient = () => {
    CustomerDialog.value = true
}

//关闭客户选择框
const closeCustomer = () => {
    CustomerDialog.value = false
}

//获取到选择的客户信息
const getCustomer = (row) => {
    const { customerId, customerCode } = { ...row }
    form.value.customerId = customerId
    form.value.customerCode = customerCode
}


</script>

<style scoped></style>
